<!-- 当前组件名： component -->
<template>
  <div class='page_component' v-loading="loading">
    <div class='page_component-container'>
      <div class='aside-left'>
        <cfCard title='' class='page-container-search'>
          <div slot='content'>
            <el-input placeholder='输入关键字进行过滤' size='small' v-model='filterText' class="bottom12" style="width: 100%;"></el-input>
            <el-tree ref='tree' :data='treeData' node-key='id' empty-text='暂无数据' highlight-current default-expand-all :expand-on-click-node="false" :filter-node-method="filterNode" @node-click='nodeClick'></el-tree>
          </div>
        </cfCard>
      </div>
      <div class='aside-right' :style="device=='mobile'?{minWidth: '100%'}:{}">
        <cfCard title='' class='page-container-search'>
          <el-form slot='content' class='searchArea' :model='searchParams' ref='searchParams' label-width='80px' inline size='small'>
            <el-form-item label='用户名称' prop="userName">
              <el-input v-model='searchParams.userName' placeholder='请输入用户名称' v-search="handleSearch"></el-input>
            </el-form-item>
            <el-form-item label='手机号码' prop="phonenumber">
              <el-input v-model='searchParams.phonenumber' placeholder='请输入手机号码' v-search="handleSearch"></el-input>
            </el-form-item>
            <el-form-item label="状 态" prop="status">
              <el-select v-model="searchParams.status" placeholder="用户状态" clearable @change="handleSearch">
                <el-option v-for="dict in sysNormalDisable" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
            <el-form-item label='创建时间' prop="dateRange">
              <el-date-picker
                v-model="searchParams.dateRange"
                style="width: 220px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期" end-placeholder="结束日期" @change="handleSearch"></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button size='mini' type='primary' @click='handleSearch'>查询</el-button>
              <el-button size='mini' @click='handleReset'>重置</el-button>
            </el-form-item>
          </el-form>
        </cfCard>
        <div class='bottom12'></div>
        <cfCard title='列表' hasTable :tableObj='tableDataObj' class='page_component-container-bottom'>
          <!--表格区域-->
          <template slot='btn'>
            <el-button size='mini' type='primary' @click='handleAdd'>新增</el-button>
            <el-button size='mini' type='warning' @click='handleExport'>导出</el-button>
          </template>
          <template slot='content'>
            <cfTable ref='cfTable' :tableDataObj='tableDataObj' :tableData='tableData'>
              <template slot='deptName'>
                <el-table-column label='部门' prop="dept.deptName" show-overflow-tooltip>
                  <span slot-scope="{row}" v-if="row.dept">{{ row.dept.deptName }}</span>
                </el-table-column>
              </template>
              <template slot='status'>
                <el-table-column label='状态' width='100px' align="center">
                  <template slot-scope="scope">
                    <el-switch
                      v-model="scope.row.status"
                      active-value="0"
                      inactive-value="1"
                      @change="handleStatusChange(scope.row)"
                    ></el-switch>
                  </template>
                </el-table-column>
              </template>
              <template slot='operate'>
                <el-table-column label='操作' width='200px' align='right'>
                  <template slot-scope="scope" v-if="scope.row.userId !== 1">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)" v-hasPermi="['system:user:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleResetPwd(scope.row)" v-hasPermi="['system:user:resetPwd']" >重置密码</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" class="delete-span" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']" >删除</el-button>
                  </template>
                </el-table-column>
              </template>
            </cfTable>
            <pagination :total='queryParams.total' :page.sync='queryParams.pageNum' :limit.sync='queryParams.pageSize' @pagination='getListFn'/>
          </template>
        </cfCard>
      </div>
    </div>
    <updateDialog v-if="dialogObj.visible" :dialogObj='dialogObj' @refresh="getListFn" />
  </div>
</template>

<script>
import updateDialog from "./updateDialog.vue";
import { listUser, exportUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus, deptTreeSelect } from "@/api/system/user";
export default {
  name: 'user',
  components: {updateDialog},
  data() {
    return {
      filterText: '',
      treeData: [],
      tableDataObj: {
        id: 'id',
        showSelection: true,
        defaultExpandAll: true,
        treeProps: {children: 'children', hasChildren: 'hasChildren'},
        option: [
          {id: 1, label: '用户编号', prop: 'userId', show: 1, align: 'center', needSlot: false},
          {id: 2, label: '用户名称', prop: 'userName', show: 1, needSlot: false},
          {id: 3, label: '用户昵称', prop: 'nickName', show: 1, needSlot: false},
          {id: 4, label: '部门', prop: 'deptName', show: 1, needSlot: true},
          {id: 5, label: '手机号码', prop: 'phonenumber', width: 100, show: 1, needSlot: false},
          {id: 6, label: '状态', prop: 'status', show: 1, needSlot: true},
          {id: 7, label: '创建时间', prop: 'createTime', width: 140, show: 1, needSlot: false},
        ]
      },
      tableData: [],
      dialogObj: {
        visible: false,
        id: null,
        title: '新增',
        width: '538px',
      },
      searchParams: {
        userName: '',
        phonenumber: '',
        status: '',
        dateRange: ""
      },
      queryParams: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      },
      loading: true
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  computed: {
    device() {
      return this.$store.getters.device;
    }
  },
  async mounted() {
    await this.getSysNormalDisable();
    this.getTreeList();
    this.getListFn();
  },
  methods: {
    nodeClick(data) {  /**树节点点击事件 */
      this.queryParams.deptId = data.id;
      this.getListFn();
    },
    async getTreeList() {
      this.loading = true;
      const res = await deptTreeSelect();
      if(res.code == 200) {
        this.treeData = res.data;
      } else {
        setTimeout(() => {
          this.loading = false;
        }, 500);
      }
    },
    filterNode(value, data) {  /**树节点过滤筛选 */
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    async getListFn() { /**获取列表数据方法*/
      this.loading = true;
      const data = {
        ...this.queryParams,
        ...this.searchParams,
        params: {
          beginTime: '',
          endTime: ''
        }
      }
      if(Array.isArray(this.searchParams.dateRange) && this.searchParams.dateRange.length) {
        data.params = {
          beginTime: this.searchParam.dateRange[0],
          endTime: this.searchParams.dateRange[1]
        }
      }
      const res = await listUser(data);
      if(res.code == 200) {
        this.tableData = res.rows;
        this.queryParams.total = res.total;
      }
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    handleAdd() { /**新增列表数据方法*/
      this.dialogObj.visible = true;
      this.dialogObj.id = '';
      this.dialogObj.title = '新增';
    },
    handleEdit(obj) { /**编辑列表数据方法*/
      this.dialogObj.visible = true;
      this.dialogObj.id = obj.userId;
      this.dialogObj.title = '编辑';
    },
    handleDelete(row) { /**删除列表数据方法*/
      const userIds = row.userId;
      this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(async()=> {
        this.loading = true;
        const res = await delUser(userIds);
        if(res.code == 200) {
          this.handleSearch();
          this.$modal.msgSuccess("删除成功");
        }
        setTimeout(() => {
          this.loading = false;
        }, 500);
      }).catch(() => {});
    },
    async handleExport() { /**导出列表数据方法*/
      this.loading = true;
      const res = await exportUser(this.searchParam);
      if(res.data && res.status == 200) {
        this.downloadFilesFn(res, `用户列表${this.formatDate('', true, '-')}.xlsx`); /**公共导出方法*/
      }
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    handleSearch() {  /**查询按钮事件*/
      this.queryParams.pageNum = 1;
      this.queryParams.total = 0;
      this.tableData = [];
      this.getListFn();
    },
    handleReset() { /**重置按钮事件*/
      this.resetForm('searchParam', ()=>{
        this.handleSearch();
      })
    },
    handleStatusChange(row) { /**用户状态修改 */
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(async()=> {
        this.loading = true;
        const res = await changeUserStatus(row.userId, row.status);
        if(res.code == 200) {
          this.$modal.msgSuccess(text + "成功");
        }
        setTimeout(() => {
          this.loading = false;
        }, 500);
      }).catch(()=> {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
      }).then(async ({ value }) => {
        const res = await resetUserPwd(row.userId, value);
        if(res.code == 200) {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        }
      }).catch(() => {});
    },
  },
}
</script>

<style scoped lang='scss'>
.page_component {
  height: 100%;
  .page_component-container {
    height: 100%;
    display: flex;
    .aside-left {
      width: 300px;
      height: 100%;
      flex-shrink: 0;
      margin-right: 12px;
      background: #fff;
      overflow: overlay;
    }
    .aside-right {
      width: 100%;
      height: 100%;
      overflow: hidden;
      overflow-y: overlay;
    }
  }
}
</style>